package com.yty.system.oauth.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yty.system.oauth.entity.SysUser;
import com.yty.system.oauth.entity.vo.SecurityUser;
import com.yty.system.oauth.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class UserDetailService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private IUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userService.findByUserName(username);
        if (user == null){
            throw new RuntimeException("用户名或密码错误！");
        }
        String password = passwordEncoder.encode(user.getPassword());
        SecurityUser securityUser  = new SecurityUser(user.getUsername(), password, AuthorityUtils.commaSeparatedStringToAuthorityList(user.getUsername()));
        securityUser.setSysUser(user);
        return securityUser;
    }

    /**
     * 获取当前用户信息
     */
    public static SysUser getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (Objects.isNull(authentication)) {
           throw new RuntimeException("请登录");
        }
        Object principal = authentication.getPrincipal();
        if (Objects.isNull(principal)) {
            throw new RuntimeException("请登录");
        }
        ObjectMapper objectMapper = new ObjectMapper();
        SysUser sysUser = ((SecurityUser) principal).getSysUser();
        return sysUser;
    }
}














